package com.stylefeng.guns.rest.modular.wz.service.impl;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.stylefeng.guns.rest.common.constant.Consts;
import com.stylefeng.guns.rest.common.constant.WzConsts;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.*;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.controller.AsyncService;
import com.stylefeng.guns.rest.modular.wz.dao.WzAdminDao;
import com.stylefeng.guns.rest.modular.wz.dao.WzUserDao;
import com.stylefeng.guns.rest.modular.wz.service.IWzUserService;
import com.stylefeng.guns.rest.modular.wz.util.wz.DateUtil;
import com.stylefeng.guns.rest.pay.ali.AlipayConfig;
import com.stylefeng.guns.rest.pay.method.PayMethod;
import com.stylefeng.guns.rest.pay.wx.util.ConstantUtil;
import com.stylefeng.guns.rest.pay.wx.util.WXUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

import static com.stylefeng.guns.rest.pay.wx.WxPrepay.createSign;
import static com.stylefeng.guns.rest.pay.wx.WxPrepay.getTransfers;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author ruiyifeng123
 * @since 2018-03-26
 */
@Service
public class WzUserServiceImpl extends ServiceImpl<WzUserMapper, WzUser> implements IWzUserService {

    @Autowired
    private WzUserFinanceRecordMapper userFinanceRecordMapper;
    @Autowired
    private WzUserCouponMapper userCouponMapper;
    @Autowired
    private WzUserAdvRecordMapper userAdvRecordMapper;
    @Autowired
    private WzUserAdvCollectionMapper UserAdvCollectionMapper;
    @Autowired
    private WzUserFixedInfoMapper userFixedInfoMapper;
    @Autowired
    private WzCouponMapper couponMapper;
    @Autowired
    private WzUserMapper userMapper;
    @Autowired
    private WzUserMessageMapper userMessageMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private WzConsts wzConsts;
    @Autowired
    private WzUserDao userDao;
    @Autowired
    private AsyncService asyncService;
    @Autowired
    private WzAdvMapper advMapper;
    @Autowired
    private PfFinanceRecordMapper pfFinanceRecordMapper;
    @Autowired
    private WzAdvUserMapper advUserMapper;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private WzUserAdvServiceImpl userAdvService;
    @Autowired
    private PfFileMapper pfFileMapper;
    @Autowired
    private WzRedpacketMapper redpacketMapper;
    @Autowired
    private WzMessageMapper messageMapper;
    @Autowired
    private WzAdvMapMapper advMapMapper;
    @Autowired
    private WzAdminDao adminDao;

    /**
     * 钱包
     * 充值
     */
    @Transactional
    public Res recharge(ParamMap p, Long userCode) throws Exception{
        //资金记录
        WzUserFinanceRecord userFinanceRecord = new WzUserFinanceRecord();
        userFinanceRecord.setId(IdWorker.getId());
        userFinanceRecord.setTargetId(userFinanceRecord.getId().toString());//唯一id号
        userFinanceRecord.setAmount(p.getInt("amount"));
        userFinanceRecord.setCreateTime(new Date());
        userFinanceRecord.setType(EnWzUserFinanceRecord.TYPE_IN.getIndex());
        userFinanceRecord.setStatus(EnWzUserFinanceRecord.STATUS_waitCheck.getIndex());
        userFinanceRecord.setUserCode(userCode);
        //返回支付数据
        if(p.getInt("payMethod") == EnWzUserFinanceRecord.payMethod_alipay.getIndex()){//支付宝充值
            userFinanceRecord.setTitle(EnWzUserFinanceRecord.TITLE_alipay_recharge.getName());
            userFinanceRecord.setPayMethod(EnWzUserFinanceRecord.payMethod_alipay.getIndex());
            userFinanceRecord.setPayType(EnWzUserFinanceRecord.TITLE_alipay_recharge.getIndex());
            int r = userFinanceRecordMapper.insert(userFinanceRecord);
            if(r > 0){
                String str = PayMethod.aliAppPay(userFinanceRecord.getId().toString(),p.getInt("amount"),"外赚充值订单");
                return Res.success(str);
            }
            return Res.fail();
        }else if(p.getInt("payMethod") == EnWzUserFinanceRecord.payMethod_weixin.getIndex()){//微信充值
            userFinanceRecord.setTitle(EnWzUserFinanceRecord.TITLE_wexin_recharge.getName());
            userFinanceRecord.setPayMethod(EnWzUserFinanceRecord.payMethod_weixin.getIndex());
            userFinanceRecord.setPayType(EnWzUserFinanceRecord.TITLE_wexin_recharge.getIndex());
            int r = userFinanceRecordMapper.insert(userFinanceRecord);
            if(r > 0){
                Map m = PayMethod.wxAppPay(p.getInt("amount"),userFinanceRecord.getId().toString(),"外赚充值订单","8.8.8.8");
                return Res.success(m);
            }
            return Res.fail();
        }
        return Res.fail("支付失败");
    }

    /**
     * 钱包
     * 提现
     */
    @Transactional
    public Res withdrawals(ParamMap p,WzUser user,WzUserFixedInfo userFixedInfo) throws Exception{
        //用户资金记录
        WzUserFinanceRecord userFinanceRecord = new WzUserFinanceRecord();
        userFinanceRecord.setId(IdWorker.getId());
        userFinanceRecord.setTargetId(userFinanceRecord.getId().toString());//唯一id号
        userFinanceRecord.setTradeNo(userFinanceRecord.getId().toString());
        //手续费
        int fee = new BigDecimal(p.getInt("amount")).multiply(new BigDecimal(wzConsts.getFee())).setScale( 0, BigDecimal.ROUND_UP ).intValue();
        //实际到账金额
        Integer realAmount = p.getInt("amount") - fee;
        if(p.getStr("payMethod").equals(EnWzUserFinanceRecord.payMethod_alipay.getName())){//支付宝提现
            //用户资金记录
            userFinanceRecord.setTitle(EnWzUserFinanceRecord.TITLE_alipay_withdrawals.getName());//支付宝提现
            userFinanceRecord.setPayMethod(EnWzUserFinanceRecord.payMethod_alipay.getIndex());//alipay
            userFinanceRecord.setPayType(EnWzUserFinanceRecord.TITLE_alipay_withdrawals.getIndex());//6
            userFinanceRecord.setRemark(EnWzUserFinanceRecord.TITLE_alipay_withdrawals.getName());//备注
        }else if(p.getStr("payMethod").equals(EnWzUserFinanceRecord.payMethod_weixin.getName())){//微信提现
            if (realAmount < 100) {
                return Res.fail("到账金额必须大于1");
            }
            //用户资金记录
            userFinanceRecord.setTitle(EnWzUserFinanceRecord.TITLE_wexin_withdrawals.getName());
            userFinanceRecord.setPayMethod(EnWzUserFinanceRecord.payMethod_weixin.getIndex());
            userFinanceRecord.setPayType(EnWzUserFinanceRecord.TITLE_wexin_withdrawals.getIndex());
            userFinanceRecord.setRemark(EnWzUserFinanceRecord.TITLE_wexin_withdrawals.getName());
        }
        //实际金额换算成小数
        double payAmount = new BigDecimal(realAmount).multiply(new BigDecimal(wzConsts.getFee())).setScale( 2, BigDecimal.ROUND_UP ).doubleValue();
        //用户资金记录
        userFinanceRecord.setAmount(p.getInt("amount"));//提现金额
        userFinanceRecord.setFee(fee);
        userFinanceRecord.setCreateTime(new Date());
        userFinanceRecord.setType(EnWzUserFinanceRecord.TYPE_OUT.getIndex());//支出
        userFinanceRecord.setUserCode(user.getUserCode());
        //资金超过限额不立即到账
//        if(p.getInt("amount") > wzConsts.getCashEveryTimeLimit()*100){
            //用户资金记录
            userFinanceRecord.setStatus(EnWzUserFinanceRecord.STATUS_WAIT_CHECK.getIndex());
            userFinanceRecord.setTitle(userFinanceRecord.getTitle() + "处理中");
            userFinanceRecord.setStatus(EnWzUserFinanceRecord.STATUS_WAIT_CHECK.getIndex());//待交易状态
            userFinanceRecord.setPayTime(new Date());
            //用户资金扣除提现金额
            user.setRewardBalance(user.getRewardBalance() - p.getInt("amount"));
            userFinanceRecord.setCashBalance(user.getCashBalance());
            userFinanceRecord.setRewardBalance(user.getRewardBalance());
            userFinanceRecord.setProfit(user.getProfit());
            boolean r = userDao.saveWithdrawals(userFinanceRecord,user);
            if(r){
                WzMessage message = new WzMessage();
                message.setAvatarUrl(user.getAvatarUrl());
                message.setCreateTime(new Date());
                message.setNickName(user.getNickName());
                message.setContent("提现"+new BigDecimal(p.getInt("amount")*0.01).intValue()+"元");
                messageMapper.insert(message);
                return Res.success();
            }
//            return Res.fail();
//        }else{
//            //正常支付
//            if(p.getStr("payMethod").equals(EnWzUserFinanceRecord.payMethod_alipay.getName())){//支付宝提现
//                int r = alipay(userFinanceRecord,userFixedInfo,payAmount,user);
//                if(r == 1){
//                    return Res.success();
//                }else{
//                    return Res.fail();
//                }
//            }else if(p.getStr("payMethod").equals(EnWzUserFinanceRecord.payMethod_weixin.getName())){//微信提现
//                int r = weixin(userFinanceRecord,userFixedInfo,realAmount,user);
//                if(r == 1){
//                    return Res.success();
//                }else if(r == 5){
//                    return Res.fail("请先去微信实名认证，才能提现!");
//                }else{
//                    return Res.fail();
//                }
//            }
//        }
        return Res.fail();
    }

    /**
     * 支付宝提现处理
     */
//    public int alipay(WzUserFinanceRecord userFinanceRecord,WzUserFixedInfo userFixedInfo,double payAmount,WzUser user) throws Exception{
//        String app_id = AlipayConfig.app_id;
//        String private_key = AlipayConfig.private_key;
//        String ali_public_key = AlipayConfig.alipay_public_key;
//        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",app_id,private_key,"json","GBK",ali_public_key,"RSA2");
//        AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
//        request.setBizContent("{" +
//                "\"out_biz_no\":\""+userFinanceRecord.getTradeNo()+"\"," +
//                "\"payee_type\":\"ALIPAY_USERID\"," +
//                "\"payee_account\":\""+userFixedInfo.getAlipayUserId()+"\"," +
//                "\"amount\":\""+payAmount+"\"," +
//                "\"payer_show_name\":\"外赚\"," +
//                "\"remark\":\"外赚提现\"" +
//                "}");
//        AlipayFundTransToaccountTransferResponse response = alipayClient.execute(request);
//        if(response.isSuccess()){
//            Long userCode = IdWorker.getId();//用户编号
//            //用户账户余额修改
//            user.setRewardBalance(user.getRewardBalance() - userFinanceRecord.getAmount());
//            userFinanceRecord.setCashBalance(user.getCashBalance());
//            userFinanceRecord.setRewardBalance(user.getRewardBalance());
//            userFinanceRecord.setProfit(user.getProfit());
//            //用户资金记录
//            userFinanceRecord.setTitle(EnWzUserFinanceRecord.TITLE_alipay_withdrawals.getName() + "成功");
//            userFinanceRecord.setPayTime(new Date());
//            userFinanceRecord.setStatus(EnWzUserFinanceRecord.STATUS_SUCCESS.getIndex());//交易成功
//            boolean r = userDao.saveWithdrawals(userFinanceRecord,user);
//            if(r){
//                return 1;
//            }
//            return 0;
//        } else {
//            if(response.getSubCode().equals("PAYER_BALANCE_NOT_ENOUGH")){
//                //用户账户余额修改
//                user.setRewardBalance(user.getRewardBalance() - userFinanceRecord.getAmount());
//                userFinanceRecord.setCashBalance(user.getCashBalance());
//                userFinanceRecord.setRewardBalance(user.getRewardBalance());
//                userFinanceRecord.setProfit(user.getProfit());
//                //用户资金记录
//                userFinanceRecord.setTitle(EnWzUserFinanceRecord.TITLE_alipay_withdrawals.getName() + "处理中");
//                userFinanceRecord.setPayTime(new Date());
//                userFinanceRecord.setStatus(EnWzUserFinanceRecord.STATUS_WAIT_CHECK.getIndex());
//                userFinanceRecord.setRemark(userFinanceRecord.getRemark() + "," +response.getSubMsg());
//                boolean r = userDao.saveWithdrawals(userFinanceRecord,user);
//                if(r){
//                    return 1;
//                }
//                return 0;
//            }else{
//                //用户资金记录
//                userFinanceRecord.setTitle(EnWzUserFinanceRecord.TITLE_alipay_withdrawals.getName() + "失败");
//                userFinanceRecord.setPayTime(new Date());
//                userFinanceRecord.setStatus(EnWzUserFinanceRecord.STATUS_FAIL.getIndex());
//                userFinanceRecord.setRemark(userFinanceRecord.getRemark() + "," +response.getSubMsg());
//                userFinanceRecord.setCashBalance(user.getCashBalance());
//                userFinanceRecord.setRewardBalance(user.getRewardBalance());
//                userFinanceRecord.setProfit(user.getProfit());
//                userFinanceRecordMapper.insert(userFinanceRecord);
//                return 2;
//            }
//        }
//    }

    /**
     * 微信提现处理
     */
//    public int weixin(WzUserFinanceRecord userFinanceRecord,WzUserFixedInfo userFixedInfo,Integer realAmount,WzUser user){
//        String key = ConstantUtil.APP_KEY;
//        String mch_id = ConstantUtil.PARTNER;
//        //金额转换
//        SortedMap<String, String> params =new TreeMap<String,String>();
//        params.put("check_name", "NO_CHECK");
//        params.put("nonce_str", WXUtil.getNonceStr());
//        params.put("partner_trade_no", userFinanceRecord.getTradeNo());
//        params.put("amount", realAmount.toString());  //最好直接前端处理完 穿过来 整数  后期计算下单速度快 容易出现问题
//        params.put("spbill_create_ip", "8.8.8.8");
//        params.put("desc", "外赚提现 ");
//        params.put("key", key);
//        params.put("mchid", mch_id);
//        params.put("mch_appid", ConstantUtil.APP_ID);//微信小程序appid
//        params.put("openid",userFixedInfo.getWeixinOpenid());
//        params.put("sign", createSign(params));
//        Map rr = getTransfers(params);
//        if(rr.get("result_code").equals("SUCCESS")){
//            //用户资金修改
//            user.setRewardBalance(user.getRewardBalance() - userFinanceRecord.getAmount());
//            userFinanceRecord.setCashBalance(user.getCashBalance());
//            userFinanceRecord.setRewardBalance(user.getRewardBalance());
//            userFinanceRecord.setProfit(user.getProfit());
//            //用户资金记录
//            userFinanceRecord.setTitle(EnWzUserFinanceRecord.TITLE_wexin_withdrawals.getName() + "成功");
//            userFinanceRecord.setPayTime(new Date());
//            userFinanceRecord.setStatus(EnWzUserFinanceRecord.STATUS_SUCCESS.getIndex());
//            boolean r = userDao.saveWithdrawals(userFinanceRecord,user);
//            if(r){
//                return 1;
//            }
//            return 0;
//        }else{
//            if(rr.get("err_code_des").equals("余额不足")){
//                //用户资金修改
//                user.setRewardBalance(user.getRewardBalance() - userFinanceRecord.getAmount());
//                //平台资金记录
//                userFinanceRecord.setPayTime(new Date());
//                userFinanceRecord.setStatus(EnWzUserFinanceRecord.STATUS_WAIT_CHECK.getIndex());
//                userFinanceRecord.setTitle(EnWzUserFinanceRecord.TITLE_wexin_withdrawals.getName() + "处理中");
//                userFinanceRecord.setRemark(userFinanceRecord.getRemark() + "," +rr.get("err_code_des"));
//                boolean r = userDao.saveWithdrawals(userFinanceRecord,user);
//                if(r){
//                    return 1;
//                }
//                return 0;
//            }else if(rr.get("err_code_des").equals("非实名用户账号不可发放")){
//                //用户资金记录
//                userFinanceRecord.setPayTime(new Date());
//                userFinanceRecord.setStatus(EnWzUserFinanceRecord.STATUS_FAIL.getIndex());
//                userFinanceRecord.setTitle(EnWzUserFinanceRecord.TITLE_wexin_withdrawals.getName() + "驳回");
//                userFinanceRecord.setRemark(userFinanceRecord.getRemark() + "," +rr.get("err_code_des"));
//                userFinanceRecordMapper.insert(userFinanceRecord);
//                return 5;
//            }else{
//                //用户资金记录
//                userFinanceRecord.setPayTime(new Date());
//                userFinanceRecord.setStatus(EnWzUserFinanceRecord.STATUS_FAIL.getIndex());
//                userFinanceRecord.setTitle(EnWzUserFinanceRecord.TITLE_wexin_withdrawals.getName() + "处理中");
//                userFinanceRecord.setRemark(userFinanceRecord.getRemark() + "," +rr.get("err_code_des"));
//                userFinanceRecordMapper.insert(userFinanceRecord);
//                return 2;
//            }
//        }
//    }


    /**
     * 礼券 .eq("status", EnWzUserCoupon.STATUS_NORMAL.getIndex()
     */
    public Res userCoupon(ParamMap p, Long userCode){
        List<WzUserCoupon> userCouponList = userCouponMapper.selectList(new EntityWrapper<WzUserCoupon>().eq("user_code",userCode).lt("end_time",new Date()));
        for(WzUserCoupon userCoupon:userCouponList){
            userCoupon.setStatus(EnWzUser.COUPON_STATUS_INVALID.getIndex());
            userCouponMapper.updateById(userCoupon);
        }
        List<WzUserCoupon>  userCoupons = userCouponMapper.selectPage(new Page<>(p.getInt("pageNum"),p.getInt("pageSize")),
                new EntityWrapper<WzUserCoupon>().eq("user_code",userCode).orderBy("status",true).orderBy("create_time",false));
        p.put("list",userCoupons);
        return Res.success(p);
    }

    /**
     * 礼券 .eq("status", EnWzUserCoupon.STATUS_NORMAL.getIndex()
     */
    public Res userCoupons(ParamMap p, Long userCode){
        List<WzUserCoupon> userCouponList = userCouponMapper.selectList(new EntityWrapper<WzUserCoupon>().eq("user_code",userCode).lt("end_time",new Date()).eq("status",1));
        for(WzUserCoupon userCoupon:userCouponList){
            userCoupon.setStatus(EnWzUser.COUPON_STATUS_INVALID.getIndex());
            userCouponMapper.updateById(userCoupon);
        }
        List<WzUserCoupon>  userCoupons = userCouponMapper.selectPage(new Page<>(p.getInt("pageNum"),p.getInt("pageSize")),new EntityWrapper<WzUserCoupon>().eq("user_code",userCode).eq("status",p.getIntMisValid("status")).orderBy("end_time",true));
        p.put("list",userCoupons);
        return Res.success(p);
    }

    /**
     * 广告收钱记录
     */
    public Res advRecord(ParamMap p, Long userCode) {
        List<WzUserAdvRecord>  userCoupons = userAdvRecordMapper.selectPage(new Page<>(p.getInt("pageNum"),p.getInt("pageSize")),
                new EntityWrapper<WzUserAdvRecord>().eq("user_code",userCode).eq("type",1).orderBy("create_time",false));
        p.put("list",userCoupons);
        return Res.success(p);
    }

    /**
     * 消息列表
     */
    public Res messageList(ParamMap p, int sendType) {
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        List<WzUserMessage>  userMessages = userMessageMapper.selectPage(new Page<>(p.getInt("pageNum"),p.getInt("pageSize")),
                new EntityWrapper<WzUserMessage>().eq("user_code",userCode).orderBy("create_time",false).eq("send_type",p.getInt("sendType")));
        p.put("list",userMessages);
        List<WzUser > userList = userMapper.selectList(new EntityWrapper<WzUser>().eq("user_code",userCode));
        if(userList.get(0).getIsRead() == 0){
            userList.get(0).setIsRead(1);
            userMapper.updateById(userList.get(0));
        }
        return Res.success(p);
    }

    /**
     * 消息阅读
     */
    public Res messageRead(ParamMap p) {
        WzUserMessage userMessage = userMessageMapper.selectById(p.getStr("userMessageId"));
        userMessage.setIsRead(1);
        userMessageMapper.updateById(userMessage);
        return Res.success();
    }


    /**
     * 用户信息认证数据保存
     */
    @Transactional
    @Override
    public boolean saveUserFixedInfo(WzUser user, WzUserFixedInfo userFixedInfo,Integer type) {
        int r = userMapper.updateById(user);
        if(r > 0){
            r = userFixedInfoMapper.updateById(userFixedInfo);
            if(r > 0){
                if(type == 1){
                    List<PfFile> files1 = pfFileMapper.selectList(new EntityWrapper<PfFile>().eq("file_url",userFixedInfo.getIdCardFrontUrl()));
                    if(files1.size() > 0){
                        files1.get(0).setStatus(EnPfFile.File_Status_Used.getIndex());
                        pfFileMapper.updateById(files1.get(0));
                    }
                    List<PfFile> files2 = pfFileMapper.selectList(new EntityWrapper<PfFile>().eq("file_url",userFixedInfo.getIdCardBackUrl()));
                    if(files2.size() > 0){
                        files2.get(0).setStatus(EnPfFile.File_Status_Used.getIndex());
                        pfFileMapper.updateById(files2.get(0));
                    }
                    List<PfFile> files3 = pfFileMapper.selectList(new EntityWrapper<PfFile>().eq("file_url",userFixedInfo.getMerchantLicenseUrl()));
                    if(files3.size() > 0){
                        files3.get(0).setStatus(EnPfFile.File_Status_Used.getIndex());
                        pfFileMapper.updateById(files3.get(0));
                    }
                }else if(type == 1){
                    List<PfFile> files3 = pfFileMapper.selectList(new EntityWrapper<PfFile>().eq("file_url",userFixedInfo.getMerchantLicenseUrl()));
                    if(files3.size() > 0){
                        files3.get(0).setStatus(EnPfFile.File_Status_Used.getIndex());
                        pfFileMapper.updateById(files3.get(0));
                    }
                }
                return true;
            }
        }
        return false;
    }


    /**
     * 用户自主发红包数据保存
     */
//    @Override
//    @Transactional
//    public boolean saveUserAdv(WzUser user, WzUserFinanceRecord userFinanceRecor, WzAdv adv) {
//        int r = userFinanceRecordMapper.insert(userFinanceRecor);
//        if(r > 0){
//            r = advMapper.insert(adv);
//            if(r > 0){
//                r = userMapper.updateById(user);
//                if(r > 0){
//                    return true;
//                }
//            }
//        }
//        return false;
//    }

    /**
     * 用户自主发红包成功数据保存
     */
//    @Override
//    @Transactional
//    public boolean saveCheckUserAdvSuccess(WzAdv adv,WzUser user) {
//        //广告
//        adv.setReleaseTime(new Date());//发布时间
//        adv.setStatus(EnWzAdv.STATUS_RELEASE_no.getIndex());//发布
//        String start = DateUtil.toString(new Date())+ " 00:00:00";
//        Date endDate = DateUtil.getDateAfter(new Date(), Integer.parseInt(Consts.rewardAverageDay));
//        String end = DateUtil.toString(endDate)+ " 00:00:00";
//        adv.setBeginTime(DateUtil.toDateTime(start));
//        adv.setEndTime(DateUtil.toDateTime(end));
//        //用户资金
//        List<WzUserFinanceRecord> userFinanceRecords = userFinanceRecordMapper.selectList(new EntityWrapper<WzUserFinanceRecord>().eq("trade_no",adv.getAdvId().toString()));
//        userFinanceRecords.get(0).setStatus(EnWzUserFinanceRecord.STATUS_SUCCESS.getIndex());
//        userFinanceRecords.get(0).setTitle(EnWzUserFinanceRecord.TITLE_Adv_Map_Repacket.getName()+"成功");
//        userFinanceRecords.get(0).setPayTime(new Date());
//        //用户广告
//        WzAdvUser advUser = new WzAdvUser();
//       advUser.setAdvId(adv.getAdvId().toString());
//       advUser.setCoverUrl(adv.getCoverUrl());
//       advUser.setTitle(adv.getTitle());
//       advUser.setSubtype(adv.getSubtype());
//       advUser.setAdCode(adv.getScreenCity());
//       advUser.setReleaseTime(new Date());
//        //用户修改
//        user.setIsRead(0);
//        if(user.getRole() != EnWzUser.ROLE_SUPER_ADMIN.getIndex()){
//            user.setRedpacketAmount(user.getRedpacketAmount() + adv.getExpense());
//        }
//        //数据保存
//        List<WzUserAdv> userAdvs = userAdvs(adv);
//        boolean f = userAdvService.insertBatch(userAdvs);
//        if(f){
//            int r = advMapper.updateById(adv);
//            if(r > 0){
//                r = userFinanceRecordMapper.updateById(userFinanceRecords.get(0));
//                if(r > 0){
//                    r = userMapper.updateById(user);
//                    if(r > 0){
//                        r = advUserMapper.insert(advUser);
//                        if(r > 0){
//                                return true;
//                        }
//                    }
//                }
//            }
//        }
//        return false;
//    }

    /**
     * 生成用户红包金额数据
     */
    public List<WzUserAdv> userAdvs(WzAdv adv){
        // remainSize 剩余的红包数量
        // remainMoney 剩余的钱 ,2,BigDecimal.ROUND_HALF_UP
        List<WzUserAdv> userAdvs = new ArrayList<>();
        int remainSize = adv.getTotalNumber();
        BigDecimal remainMoney = new BigDecimal(adv.getTotalReward()*0.01);
        int peilv = remainSize/200;
        if(peilv >= 25){
            peilv = 25;
        }else if(peilv < 10){
            peilv = 10;
        }
        int number = remainSize;
        for(int i = 1;i <= number;i++){
            WzUserAdv userAdv = new WzUserAdv();
            userAdv.setSort(i);
            userAdv.setAdvId(adv.getAdvId());
            if (remainSize == 1) {
                remainSize--;
                userAdv.setReward(remainMoney.multiply(new BigDecimal("100")).setScale(0,   BigDecimal.ROUND_HALF_UP).intValue());
                userAdvs.add(userAdv);
                break;
            }
            double min  = 0.01;
            BigDecimal b = remainMoney.divide(new BigDecimal(remainSize),2, BigDecimal.ROUND_HALF_EVEN);
            BigDecimal max = new BigDecimal("0");
            Random r  = new Random();
                int num = r.nextInt(number);
                double ratio = remainSize*0.18;
                if(0<num && num <= ratio){
                    ratio = remainSize*0.01;
                    if(0<num && num <= ratio){
                        max = b.multiply(new BigDecimal(peilv));
                    }else{
                        if(b.compareTo(new BigDecimal(0.1)) == -1){
                            max = b.multiply(new BigDecimal(peilv));
                        }else{
                            BigDecimal gg = b.subtract(new BigDecimal(0.09)).setScale(2, BigDecimal.ROUND_HALF_EVEN);
                            BigDecimal g = new BigDecimal(peilv).subtract(gg.multiply(new BigDecimal(100))).setScale(0, BigDecimal.ROUND_HALF_EVEN);
                            if(g.compareTo(new BigDecimal(6)) == -1){
                                g = new BigDecimal(6);
                            }
                            max = b.multiply(g);
                        }
                    }
                }else{
                    if(i < remainSize/2){
                        max = b.multiply(new BigDecimal("1.4"));
                    }else{
                        max = b.multiply(new BigDecimal("1.8"));
                    }
                }
            BigDecimal m  = new BigDecimal(r.nextDouble()*max.doubleValue());
            double money = m.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
            money = money <= min ? 0.01: money;
            remainSize--;
            remainMoney = remainMoney.subtract(new BigDecimal(money)).setScale(2,   BigDecimal.ROUND_HALF_UP);
            userAdv.setReward(new BigDecimal(money).multiply(new BigDecimal("100")).setScale(0,   BigDecimal.ROUND_HALF_UP).intValue());
            userAdvs.add(userAdv);
        }
        return userAdvs;
    }

    /**
     * 用户自主发红包失败数据保存
     */
//    @Transactional
//    public boolean saveCheckUserAdvFail(WzAdv adv,WzUser user) {
//        //广告
//        adv.setStatus(EnWzAdv.STATUS_REJECT.getIndex());//驳回
//        //用户资金
//        WzUserFinanceRecord userFinanceRecord = new WzUserFinanceRecord();
//        userFinanceRecord.setStatus(EnWzUserFinanceRecord.STATUS_SUCCESS.getIndex());//状态:成功
//        userFinanceRecord.setAmount(adv.getExpense());//金额
//        userFinanceRecord.setTitle(EnWzUserFinanceRecord.TITLE_Adv_Map_Repacket.getName()+"驳回");//标题
//        userFinanceRecord.setPayTime(new Date());//支付时间
//        userFinanceRecord.setUserCode(adv.getUserCode());//用户编号
//        userFinanceRecord.setType(EnWzUserFinanceRecord.TYPE_IN.getIndex());//入账
//        userFinanceRecord.setPayType(EnWzUserFinanceRecord.TITLE_Adv_Map_Repacket.getIndex());//金额类型
//        userFinanceRecord.setCreateTime(new Date());//创建时间
//        userFinanceRecord.setPayMethod(EnWzUserFinanceRecord.payMethod_wz.getIndex());//交易渠道:wz
//        //用户资金返还
//        user.setCashBalance(user.getCashBalance() + adv.getExpense());
//        user.setIsRead(0);
//        //用户通知消息
//        int r = advMapper.updateById(adv);
//        if(r > 0){
//            r = userMapper.updateById(user);
//            if(r > 0){
//                r = userFinanceRecordMapper.insert(userFinanceRecord);
//                if(r > 0){
//                        return true;
//                }
//            }
//        }
//        return false;
//    }

//    @Override
//    @Transactional
//    public boolean updateUserAdv(WzUser user, WzUserFinanceRecord userFinanceRecor, WzAdv adv) {
//        int r = userFinanceRecordMapper.insert(userFinanceRecor);
//        if(r > 0){
//            r = advMapper.updateById(adv);
//            if(r > 0){
//                r = userMapper.updateById(user);
//                if(r > 0){
//                    return true;
//                }
//            }
//        }
//        return false;
//    }

    public Res indexMessageList() {
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        String sql = "user_message_id As userMessageId,title,type,jump_target As jumpTarget";
        List<Map<String, Object>>  userMessages = userMessageMapper.selectMaps(new EntityWrapper<WzUserMessage>().setSqlSelect(sql).eq("user_code",userCode).eq("is_read",0).orderBy("create_time",false));
        return Res.success(userMessages);
    }
}
